package com.yb.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
@Aspect
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.yb.blog.controller..*.*(..))")
    public void log(){

    }

//    @Before("log()")
//    public void Before(JoinPoint joinPoint){
//        String className = joinPoint.getTarget().getClass().getSimpleName();
//        String methodName = joinPoint.getSignature().getName();
//        List list = Arrays.asList(joinPoint.getArgs());
//        logger.info("className:【{}】,methodName:【{}】,args:【{}】",className,methodName,list);
//    }
//
//    @After("log()")
//    public void after(JoinPoint joinPoint){
//
//    }

    @Around("log()")
    public Object around(JoinPoint joinPoint){
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        List list = Arrays.asList(joinPoint.getArgs());
        logger.info("=============== 开始执行方法:{}.{} ===============",className,methodName);
        logger.info("传入参数：{}",list);
        long startTime = System.currentTimeMillis();
        Object res = null;
        try {
            res = ((ProceedingJoinPoint)joinPoint).proceed();
            logger.info("执行结果为：{}", res);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            logger.error("执行方法{}.{}异常，异常原因：{}",className,methodName,throwable.getMessage());
        }finally {
            long endTime = System.currentTimeMillis();
            logger.info("=============== 执行方法{}.{} 结束，耗时：{} ===============",className,methodName,endTime-startTime);
        }
        return res;
    }




}
